<?php
// $Id: power_menu.forms.inc,v 1.5 2010/11/16 08:09:43 rapsli Exp $

/**
 * @file
 * manipulation of the forms
 */

function _power_menu_form_alter(&$form, &$form_state) {
  $menu_name = $form['menu']['original_item']['#value']['menu_name'];
  $form['#submit'][] = 'power_menu_form_menu_edit_item_submit';

  // let's see if there is an alias for this path
  // if so we give the possibility to add an alias right away
  // instead of having to go to the alias page to set one up
  if (module_exists('path')) {
    $result = db_query("SELECT * FROM {url_alias} WHERE src='%s'", $form['menu']['link_path']['#default_value']);
    $alias = '';
    while ($row = db_fetch_object($result)) {
      $alias[$row->pid] = $row->dst;
    }

    // incase there is more than one alias we are going to display some additional information
    if (count($alias) > 1) {
      //drupal_set_message(t('There is more than one alias for the path. Please contact the site administrator. There are @number aliases for this link.', array('@number' => count($alias))), 'warning');
      $ar_others = $alias;
      $description = '<br/><i>' . t('The following aliases are also pointing to this path:') . '</i>';

      $i = 0;
      foreach ($ar_others as $key => $item) {
        $ar_others[$key] = l($item, "admin/build/path/edit/$key");
      }
      $description .= theme('item_list', $ar_others);
    }
    elseif (count($alias) == 1) {
      $ar_others = $alias;
      if (is_array($ar_others)) {
        foreach ($ar_others as $key => $item) {
          $description .= t('Edit the alias here:') . ' ' . l($item, "admin/build/path/edit/$key");
        }
      }
    }
    $description = t('There are currently some issues with multilingual setup. This option is therefor disabled untill we can fix this.') . ' ';
    $description .= t('Please use the !default_alias_manager to create aliases.', array('!default_alias_manager' => l(t('default alias manager'), 'admin/build/path/add')));

    $alias = ($alias)?array_shift($alias):'';
    $form['menu']['alias'] = array(
      '#type' => 'textfield',
      '#title' => t('Alias'),
      '#weight' => -3,
      '#description' => t('Automatically setup an alias. This relies on the core path module.') . $description,
      '#default_value' => $alias,
      '#disabled' => TRUE,
    );
    $form['menu']['link_path']['#weight'] = -5;
    $form['menu']['link_title']['#weight'] = -4;

  }

  $ar_am = power_menu_get_tids($form['menu']['mlid']['#value']);
  if (is_array($ar_am)) {
    foreach ($ar_am as $item) {
      if ($item->nodetype != '') {
        $ar_existing_nodetypes[] = $item->nodetype;
      }
      if (is_numeric($item->tid)) {
        $ar_existing_tids[] = $item->tid;
      }
    }
  }

  // *************** Taxonomy ****************************
  // We give the user the option to either add or link a menu item with a taxonomy term
  if (module_exists('taxonomy') && variable_get('power_menu_taxonomy_navigation', '') != '') {
    $form['menu']['taxonomy_create'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create Taxonomy term'),
      '#weight' => 10,
      '#description' => t("The name of the taxonomy term is going to be the title of the menu link. Incase there is already a term with the same name, it's not going to be created."),
    );

    if (in_array($menu_name, array_filter(power_menu_get_pm_menus()))) {
      $result = db_query("SELECT tid FROM {power_menu} WHERE mlid<>%d AND tid<>0 AND menu_name like '%s'", $form['menu']['mlid']['#value'], $menu_name);
      $ar_taken = array();
      while ($row = db_fetch_object($result)) {
        $ar_taken[] = $row->tid;
      }

      $terms = taxonomy_get_tree(variable_get('power_menu_taxonomy_navigation', ''));
      $options = array('' => t('- None selected -'));

      // create the hierarchy and make sure that we mark the ones that are not selectable, because they already belong to an other menu item
      if ($terms) {
        foreach ($terms as $term) {
          if (!in_array($term->tid, $ar_taken)) {
            $choice = new stdClass();
            $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
            $options[] = $choice;
          }
          else {
            $choice = new stdClass();
            $choice->option = array('' => str_repeat('-', $term->depth) . $term->name . ' ' . t('-already in use-'));
            $options[] = $choice;
          }
        }
      }

      $form['menu']['taxonomy_link'] = array(
        '#type' => 'select',
        '#title' => t('Link to existing term'),
        '#weight' => 11,
        '#multiple' => TRUE,
        '#options' => $options,
        '#default_value' => $ar_existing_tids,
        '#description' => t('Choose a taxonomy term. When displaying a node that has the selected taxonomy term, this menu item will set to active. A term can only belong to one menu item, meaning if there are no terms available they are already asigned to other menu items.'),
      );
    }

  }
  else {
    drupal_set_message(t("You don't have the taxonomy enabled or not configured it properly. <a href='!link'>admin/settings/power_menu</a>", array('!link' => url('admin/settings/power_menu'))));
  }

  // ***************** Nodetype *******************************
  // we are going to get all the nodetypes and look which ones are not already assigned to a menu item
  $result = db_query("SELECT nodetype FROM {power_menu} WHERE mlid<>%d AND menu_name like '%s' GROUP BY nodetype", $form['menu']['mlid']['#value'], $menu_name);
  $ar_taken = array();
  while ($row = db_fetch_object($result)) {
    $ar_taken[] = $row->nodetype;
  }
  $options = array('' => t('- None selected -'));
  foreach (node_get_types() as $nodetype) {
    if (!in_array($nodetype->type, $ar_taken)) {
      $options[$nodetype->type] = $nodetype->name;
    }
  }
  $form['menu']['nodetype'] = array(
    '#type' => 'select',
    '#title' => t('Active when node of type... is displayed'),
    '#weight' => 12,
    '#multiple' => TRUE,
    '#options' => $options,
    '#default_value' => $ar_existing_nodetypes,
    '#description' => t('You can select a nodetype. If a node of the selected nodetype is being displayed, then this menu item will be marked active. The nodetypes that are not available for selection are already being used for an other menu item.'),
  );

  // finding properties that are predefined by the system in the properties folder
  $dir = dir(drupal_get_path('module', 'power_menu') . '/properties');
  $properties = array();
  while ($filename = $dir->read()) {
    $file = $dir->path . '/' . $filename;
    if (filetype($file) == 'file') {
      include_once($file);
      $properties = array_merge($properties, module_invoke(str_replace(".inc", '', $filename), 'power_menu_properties'));
    }
  }
  $dir->close();
  $properties = array_merge($properties, module_invoke_all('power_menu_properties'));
  cache_set('power_menu_properties', $properties, 'cache');

  // setting up properties
  $form['properties'] = array(
    '#type' => 'fieldset',
    '#title' => t('Properties'),
    '#weight' => -1,
    '#collapsed' => FALSE,
    '#collapsible' => TRUE,
    '#tree' => TRUE,
    '#description' => t("Properties can be inherited. If no property is set, it's going taketo display the property of the parent menu item."),
  );

  foreach ($properties as $prop) {
      $form['properties'][$prop['property_name']] = array(
        '#type' => 'textarea',
        '#title' => $prop['property_name'],
        '#default_value' => $prop['property_load']($form['menu']['mlid']['#value'], TRUE),
        '#description' => $prop['description'],
      );
      $form['#submit'][] = $prop['admin_submit'];
  }
}

/**
 * Callback function when menu_edit_item form is being submitted
 * @param array $form
 * @param array $form_state
 */
function _power_menu_form_menu_edit_item_submit($form, &$form_state) {
  $mlid = check_plain($form_state['values']['menu']['mlid']);
  $link_path = $form_state['values']['menu']['link_path'];
  $menu_name = $form_state['values']['menu']['original_item']['menu_name'];

  // delete existing entries for the menu item
  db_query("DELETE FROM {power_menu} WHERE mlid=%d", $mlid);

  // *********** New Alias *************************
  // let's create an alias
  if (!empty($form_state['values']['menu']['alias'])) {
    $existing_alias = db_fetch_object(db_query("SELECT * FROM {url_alias} WHERE src='%s' and dst='%s'", $form_state['values']['menu']['link_path'], $form_state['values']['menu']['alias']));
    $alias = check_url($form_state['values']['menu']['alias']);
    //path_set_alias($link_path, $alias, $existing_alias->pid);
  }

  // *********** New Taxonomy ***********************
  // we are going to try to create a new taxonomy term
  if ($form_state['values']['menu']['taxonomy_create'] == 1) {
    // TODO: What about the hierarchy? there is going to be a problem if the same taxonomy term but in a different hierarchy is available
    if (!power_menu_get_term_by_name_vocab($form_state['values']['menu']['link_title'], variable_get('power_menu_taxonomy_navigation', ''))) {
      $term = array(
        'vid' => variable_get('power_menu_taxonomy_navigation', ''), // Voacabulary ID
        'name' => $form_state['values']['menu']['link_title'], // Term Name
      );
      taxonomy_save_term($term);

      // we are going to try to replace the token in the path
      $tid = db_last_insert_id('{term_data}', 'tid');
      _power_menu_replace_tid_in_path($tid, $mlid, $link_path);

      $ar = array(
        'mlid' => $mlid,
        'tid' => $term['tid'],
        'mid' => $mlid . $term['tid'],
      );
      drupal_write_record('power_menu', $ar);
    }
    else {
      drupal_set_message(t('There is already a taxonomy term with the specified title'), 'warning');
    }
  }

  // *********** Taxonomy ***********************
  if ($form_state['values']['menu']['taxonomy_link']) {
    $ar_tids = $form_state['values']['menu']['taxonomy_link'];
    foreach ($ar_tids as $tid) {
      if (is_numeric($tid)) {
        $ar = array(
          'mlid' => $mlid,
          'nodetype' => '',
          'tid' => $tid,
          'path' => str_replace("[tid]", $tid, $link_path),
          'mid' => $mlid . $tid,
          'menu_name' => $menu_name,
        );
        drupal_write_record('power_menu', $ar);
        _power_menu_replace_tid_in_path($tid, $mlid, $link_path);
      }
    }
  }

  // *********** Nodetype ***********************
  // we are going to connect a menu to an existing term
  // and let's check if we have a nodetype that we want to connect with the menu item
  if ($form_state['values']['menu']['nodetype']) {
    $mlid = check_plain($form_state['values']['menu']['mlid']);
    foreach ($form_state['values']['menu']['nodetype'] as $nt) {
      if ($nt != '') {
        $ar = array(
          'mlid' => $mlid,
          'nodetype' => $nt,
          'path' => $link_path,
          'tid' => 0,
          'mid' => $mlid . $nt,
          'menu_name' => $menu_name,
        );
        drupal_write_record('power_menu', $ar);
      }
    }
  }
}

function _power_menu_form_overview_alter(&$form, &$form_state) {
  // finding properties that are predefined by the system in the properties folder
  $dir = dir(drupal_get_path('module', 'power_menu') . '/properties');
  $properties = array();
  while ($filename = $dir->read()) {
    $file = $dir->path . '/' . $filename;
    if (filetype($file) == 'file') {
      include_once($file);
      $properties = array_merge($properties, module_invoke(str_replace(".inc", '', $filename), 'power_menu_properties'));
    }
  }
  $dir->close();
  $properties = array_merge($properties, module_invoke_all('power_menu_properties'));
  cache_set('power_menu_properties', $properties, 'cache');

  // setting up properties
  $form['properties'] = array(
    '#type' => 'fieldset',
    '#title' => t('Properties'),
    '#weight' => -1,
    '#collapsed' => FALSE,
    '#collapsible' => TRUE,
    '#tree' => TRUE,
    '#description' => t("Properties can be inherited. If no property is set, it's going taketo display the property of the parent menu item."),
  );

  foreach ($properties as $prop) {
      $form['properties'][$prop['property_name']] = array(
        '#type' => 'textarea',
        '#title' => $prop['property_name'],
        '#default_value' => $prop['property_load'](0, TRUE),
        '#description' => $prop['description'],
      );
      $form['#submit'][] = $prop['admin_submit'];
  }
}